﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebEntities;
using WebEntities.Models.Framework;
using System.Web.Security;

namespace com.subb.WebFramework
{
    public enum MemberVerifyResult
    {
        Success = 1,
        Failure,
        Locked
    }

    public class FW_MemberDAL
    {
        private const string PSW_SALT = "www.corp.com";

        public List<FW_Member> GetAllMembers(int start, int limit, out int ttlCount)
        {
            ttlCount = 0;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                ctx.ContextOptions.LazyLoadingEnabled = false;
                var query = ctx.FW_Member.OrderBy(c => c.MemberID);
                ttlCount = query.Count();
                List<FW_Member> memlist = query.Skip(start).Take(limit).ToList();
                return memlist;
            }
        }

        public List<FW_Member> GetAllMembers(byte memType, int start, int limit, out int ttlCount)
        {
            ttlCount = 0;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                ctx.ContextOptions.LazyLoadingEnabled = false;
                var query = ctx.FW_Member.Where(c => c.MemType == memType).OrderBy(c => c.MemberID);
                ttlCount = query.Count();
                List<FW_Member> memlist = query.Skip(start).Take(limit).ToList();
                return memlist;
            }
        }

        public FW_Member GetMemberByGID(string gid)
        {
            using (SugardbEntities ctx = new SugardbEntities())
            {
                ctx.ContextOptions.LazyLoadingEnabled = false;
                FW_Member member = ctx.FW_Member.SingleOrDefault(c => c.GID.Equals(gid, StringComparison.CurrentCultureIgnoreCase));
                return member;
            }
        }

        public FW_Member GetMember(string memId)
        {
            using (SugardbEntities ctx = new SugardbEntities())
            {
                ctx.ContextOptions.LazyLoadingEnabled = false;
                FW_Member member = ctx.FW_Member.SingleOrDefault(c => c.MemberID.Equals(memId, StringComparison.CurrentCultureIgnoreCase));
                return member;
            }
        }

        public FW_Member GetMemberByNickName(string nickName)
        {
            using (SugardbEntities ctx = new SugardbEntities())
            {
                ctx.ContextOptions.LazyLoadingEnabled = false;
                FW_Member member = ctx.FW_Member.SingleOrDefault(c => c.NickName.Equals(nickName, StringComparison.CurrentCultureIgnoreCase));
                return member;
            }
        }

        /// <summary>
        /// 检查用户ID是否可用。
        /// </summary>
        /// <param name="memName">检查的用户名</param>
        /// <returns>true:已存在，false:可使用</returns>
        public bool HasExistMemberID(string memId)
        {
            bool result = false;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                int count = ctx.FW_Member.Where(c => c.MemberID.Equals(memId, StringComparison.CurrentCultureIgnoreCase)).Count();
                result = count > 0 ? true : false;
            }
            return result;
        }

        /// <summary>
        /// 检查用户昵称是否可用。
        /// </summary>
        /// <param name="nickName">检查的昵称</param>
        /// <returns>true:已存在，false:可使用</returns>
        public bool HasExistNickName(string nickName)
        {
            bool result = false;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                FW_Member member = ctx.FW_Member.FirstOrDefault(c => c.NickName.Equals(nickName, StringComparison.CurrentCultureIgnoreCase));
                if (member != null)
                {
                    result = true;
                }
            }
            return result;
        }

        /// <summary>
        /// 检查用户邮箱地址是否存在。
        /// </summary>
        /// <param name="memId"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool ExistEmail(string email)
        {
            bool result = false;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                int count = ctx.FW_Member.Where(c => (c.Email ?? string.Empty).Equals(email.Trim(), StringComparison.CurrentCultureIgnoreCase)).Count();
                result = (count > 0) ? true : false;
                
            }
            return result;
        }

        public void CreateMember(Member v_member)
        {
            using (SugardbEntities ctx = new SugardbEntities())
            {
                string password = v_member.MemPasswd + PSW_SALT;
                string encpsw = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5");
                FW_Member member = new FW_Member
                {
                    GID = Guid.NewGuid().ToString(),
                    MemberID = v_member.MemberID.Trim(),
                    MemPasswd = encpsw,
                    NickName = v_member.NickName,
                    CreateTime = DateTime.Now,
                    Email = v_member.Email == null ? null : v_member.Email.Trim(),
                    LoginCount = 0,
                    MemStatus = v_member.MemStatus,
                    MemType = v_member.MemType,
                    HeadPic = v_member.HeadPic,
                    EmailValid = v_member.EmailValid
                };
                ctx.FW_Member.AddObject(member);
                ctx.SaveChanges();
            }
        }

        public bool UpdateMember(string gid, Member v_member)
        {
            bool result = false;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                FW_Member member = ctx.FW_Member.SingleOrDefault(c => c.GID.Equals(gid, StringComparison.CurrentCultureIgnoreCase));
                if (member != null)
                {
                    if (!member.MemPasswd.Equals(v_member.MemPasswd, StringComparison.CurrentCultureIgnoreCase))
                    {
                        string password = v_member.MemPasswd + PSW_SALT;
                        string encpsw = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5");
                        member.MemPasswd = encpsw;
                    }
                    member.NickName = v_member.NickName.Trim();
                    member.Email = v_member.Email == null ? null : v_member.Email.Trim();
                    member.MemStatus = v_member.MemStatus;
                    member.MemType = v_member.MemType;
                    member.HeadPic = v_member.HeadPic;
                    member.EmailValid = v_member.EmailValid;
                    ctx.SaveChanges();
                    result = true;
                }
            }
            return result;
        }

        public bool RemoveMember(string gid)
        {
            bool result = false;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                FW_Member member = ctx.FW_Member.SingleOrDefault(c => c.GID.Equals(gid, StringComparison.CurrentCultureIgnoreCase));
                if (member != null)
                {
                    ctx.FW_Member.DeleteObject(member);
                    ctx.SaveChanges();
                    result = true;
                }
            }
            return result;
        }

        public MemberVerifyResult VerifyMember(string userName, string password, out DateTime lastLoginTime)
        {
            lastLoginTime = DateTime.Now;
            MemberVerifyResult result = MemberVerifyResult.Failure;
            FW_Member member = GetMember(userName);
            if (member != null)
            {
                if (member.MemStatus == 1)
                {
                    string cipherPsw = FormsAuthentication.HashPasswordForStoringInConfigFile(password + PSW_SALT, "md5");
                    if (member.MemPasswd.Equals(cipherPsw, StringComparison.CurrentCultureIgnoreCase))
                    {
                        result = MemberVerifyResult.Success;
                        lastLoginTime = member.LastLoginTime ?? DateTime.Now;
                    }
                }
                else
                {
                    result = MemberVerifyResult.Locked;
                }
            }
            return result;
        }

        /// <summary>
        /// 登录成功后更新登录信息
        /// </summary>
        public void LoginSuccess(string memId)
        {
            using (SugardbEntities ctx = new SugardbEntities())
            {
                FW_Member member = ctx.FW_Member.SingleOrDefault(c => c.MemberID.Equals(memId, StringComparison.CurrentCultureIgnoreCase));
                if (member != null)
                {
                    member.LastLoginTime = DateTime.Now;
                    int lcount = member.LoginCount ?? 0;
                    lcount++;
                    member.LoginCount = lcount;
                    ctx.SaveChanges();
                }
            }
        }

        public void CreateEmailVcode(string memId, string vcode, string receiver, string ipAddr)
        {
            using (SugardbEntities ctx = new SugardbEntities())
            {
                var query = ctx.FW_ValidCode.Where(c => c.MemberID.Equals(memId, StringComparison.CurrentCultureIgnoreCase) && (c.IsUsed ?? 0) == 0 && (c.IsDelete ?? 0) == 0);
                List<FW_ValidCode> vcodeList = query.ToList();
                foreach (var vc in vcodeList)
                {
                    vc.IsDelete = 1;
                }
                FW_ValidCode newVcode = new FW_ValidCode
                {
                    MemberID = memId,
                    VType = "Email",
                    Receiver = receiver,
                    ValidCode = vcode,
                    CreateTime = DateTime.Now,
                    IsUsed = 0,
                    IsDelete = 0,
                    IpAddr = ipAddr
                };
                ctx.FW_ValidCode.AddObject(newVcode);
                ctx.SaveChanges();
            }
        }

        public bool VerfiyEmailVcode(string vcode, out string memId)
        {
            bool result = false;
            memId = string.Empty;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                var query = ctx.FW_ValidCode.Where(c => c.ValidCode.Equals(vcode, StringComparison.CurrentCultureIgnoreCase) && c.IsDelete == 0 && c.IsUsed == 0);
                FW_ValidCode valCode = query.FirstOrDefault();
                if (valCode != null)
                {
                    FW_Member member = ctx.FW_Member.FirstOrDefault(c => c.MemberID.Equals(valCode.MemberID, StringComparison.CurrentCultureIgnoreCase));
                    if ((member.EmailValid ?? 0) == 0)
                    {
                        valCode.IsUsed = 1;
                        ctx.SaveChanges();
                        memId = valCode.MemberID;
                        result = true;
                    }
                }
            }
            return result;
        }

        public void EmailBinding(string memId)
        {
            using (SugardbEntities ctx = new SugardbEntities())
            {
                FW_Member member = ctx.FW_Member.FirstOrDefault(c => c.MemberID.Equals(memId, StringComparison.CurrentCultureIgnoreCase));
                if (member != null)
                {
                    member.EmailValid = 1;
                    ctx.SaveChanges();
                }
            }
        }

        public List<FW_ValidCode> GetMemberVcode(string memId)
        {
            using (SugardbEntities ctx = new SugardbEntities())
            {
                var query = ctx.FW_ValidCode.Where(c => c.MemberID.Equals(memId, StringComparison.CurrentCultureIgnoreCase));
                List<FW_ValidCode> vcodeList = query.ToList();
                return vcodeList;
            }
        }

        /// <summary>
        /// 检查能否重发邮箱验证邮件
        /// </summary>
        public bool CheckResendValidEmail(string memId, string email, string ip, out string msg)
        {
            bool result = false;
            msg = string.Empty;
            using (SugardbEntities ctx = new SugardbEntities())
            {
                FW_Member member = ctx.FW_Member.FirstOrDefault(c => c.MemberID.Equals(memId, StringComparison.CurrentCultureIgnoreCase));
                if (member != null)
                {
                    FW_ValidCode valCode = ctx.FW_ValidCode.FirstOrDefault(c => c.Receiver.Equals(email, StringComparison.CurrentCultureIgnoreCase) && c.IsUsed == 1);
                    if (valCode != null)
                    {
                        msg = "邮箱地址已被使用，不能重复验证。";
                    }
                    else
                    {
                        result = true;
                        msg = "重新发送.";
                    }
                }
                else
                {
                    msg = "用户还没有注册，不能验证邮箱地址。";
                }
            }
            return result;
        }
    }
}
